package com.jackrain.nea.dao;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.stereotype.Component;
import org.springframework.ldap.AuthenticationException;

/**
 * @author xubin
 * 2017-11-23
 */
@Slf4j
@Component
public class UserReposity {

    @Autowired
    private LdapTemplate ldapTemplate;


    public boolean authenticate(String sAMAccountName,String password) {
        AndFilter filter=new AndFilter();
        filter.and(new EqualsFilter("sAMAccountName",sAMAccountName));
        try {
            return ldapTemplate.authenticate("",filter.encode(),password);
        }catch (AuthenticationException e){
            log.error(e.getMessage(),e);
            return false;
        }

    }

    @Bean
    public LdapTemplate ldapTemplate(@Autowired LdapContextSource contextSource){
        LdapTemplate ldapTemplate=new LdapTemplate(contextSource);
        ldapTemplate.setIgnorePartialResultException(true);
        return ldapTemplate;
    }


    @Bean
    public LdapContextSource ldapContextSource(@Value("${ldap.urls}")String ldapUrls,@Value("${ldap.base}")String base,
                                               @Value("${ldap.username}")String username ,@Value("${ldap.password}")String password){
        LdapContextSource source=new LdapContextSource();
        source.setUrl(ldapUrls);
        source.setBase(base);
        source.setUserDn(username);
        source.setPassword(password);
        return source;
    }

}
